<script setup>
import { ref, onMounted, watch, computed, onBeforeMount, nextTick } from 'vue'
import { generateUUID, go2Link, go2Router, copyJSON, getDeviceType, bgColors, isPhone, uploadFile, isNotEmpty, isEmpty, saveUser2Db } from '@/plugins/util.js'
import { useRouter } from 'vue-router'
import { useUser } from '@/composition/useUser'
import { useConfirm } from '@/composition/useConfirm'
import { useToast } from '@/composition/useToast'
import { getImgsApi, getByImgsApi, getImgTagsApi } from '@/plugins/http/api/common'
import { setUserExtInfoApi } from '@/plugins/http/api/user'
import serverConfig from "@/plugins/http/config";

const router = useRouter();
const { user, getBgImgUrlPcDefault, getBgImgUrlMobileDefault, setBg } = useUser();
const { showConfirm } = useConfirm()
const { successToast, errorToast, infoToast } = useToast();

let deviceType = getDeviceType();
// 非响应
let bgInfo = copyJSON(user.value.extInfo.bg[deviceType])
// bgSwitch.value = bgInfo.showType !== 'none';
// bgImgList.value = copyJSON(bgInfo.urls || []);
// autoChangeBg.value = copyJSON(bgInfo.autoChangeBg || {});

const uploadEle = ref(null)

const byImgHoverIndex = ref(null)
const resetDialog = ref(false)
const bgImgList = ref(bgInfo.urls || [])
const bgSwitch = ref(bgInfo.showType !== 'none')
const autoChangeBg = ref(bgInfo.autoChangeBg || {})
const delDialog = ref(false)
const activeBgImgIndex = ref(-1)
const openItem = ref({})
const editDialog = ref(false)
const formData = ref({
    companyName: '',
    clockNum: '',
    telNum: '',

    address: '',
    revName: '',
    contactNum: '',
    remark: ''
})
const valid = ref(false)
const notNullRules = ref([
    v => !!v || '不能为空'
    // v => v.length <= 10 || 'Name must be less than 10 characters',
])
const uploadImg = ref('')
const page = ref({
    pageNo: 1,
    pageSize: 6
})
const slider = ref({ label: '面板透明度', val: 3, color: '', hint: '数值越大，越透明', max: 10, min: 0 })
const cardTransparency = ref(2)
const navList = ref([
    {
        uuid: generateUUID(),
        title: '图片背景'
    },
    {
        uuid: generateUUID(),
        title: '颜色背景'
    },
    {
        uuid: generateUUID(),
        title: '自由设置'
    }
])


const activeTabIndex = ref(0)
const showList = ref([])

// const scaleImgStr = 'scale=0.5';
const scaleImgStr = 'width=512';


const navClick = (index, $event) => {
    // console.log(index);
    // console.log($event.target);
    let elementNodeListOf = document.querySelectorAll('[name=nav]');
    elementNodeListOf.forEach((ele) => {
        ele.classList.remove('border-b-4', 'text-green-500');
    })
    $event.target.classList.add('border-b-4', 'text-green-500');
    activeTabIndex.value = index;
}

const mytagClick = (index, $event) => {
    // console.log(index);
    // console.log($event.target);
    let elementNodeListOf = document.querySelectorAll('[name=tagnav]');
    elementNodeListOf.forEach((ele) => {
        ele.classList.remove('border-b-4', 'text-green-500');
    })
    $event.target.classList.add('border-b-4', 'text-green-500');

    getImgsEnd.value = false
    page.value.pageNo = 1

    activeMyTag.value = myBgTags.value[index].title
    getBgImg(myBgTags.value[index].title)
}

const checkBg = (index) => {
    bgImgList.value[index].checked = !bgImgList.value[index].checked;
    bgInfo.urls = bgImgList.value;
    bgInfo.showType = 'url';
    setBgInfo();
    activeBgImgIndex.value = index;
    // openItem.value = copyJSON(bgImgList.value[index]);
    // saveBgImgUrl();
}

const openEditModel = (index) => {
    activeBgImgIndex.value = index;
    editDialog.value = true;
    openItem.value = copyJSON(bgImgList.value[index]);
    // console.log(openItem.value)
}

const openDelModel = (index) => {
    activeBgImgIndex.value = index;
    // this.delDialog = true;
    showConfirm({ content: '确认删除吗？' }).then(() => {
        delBgImgUrl();
    }).catch(() => { })
    //     this.$confirm({
    //         content: '确认删除吗？',
    //     }, () => {
    //         this.delBgImgUrl();
    //     });
}

const delBgImgUrl = () => {
    bgImgList.value.splice(activeBgImgIndex.value, 1);
    bgInfo.urls = bgImgList.value;
    bgInfo.showType = 'url';
    setBgInfo();
}

const getImgsEnd = ref(false);

//  响应式
// let bgInfo;
const init = () => {
    // cardTransparency.value = user.value.extInfo.common.cardTransparency;
    // let deviceType = getDeviceType();
    // bgInfo = user.value.extInfo.bg[deviceType]
    // bgSwitch.value = bgInfo.showType !== 'none';
    // bgImgList.value = copyJSON(bgInfo.urls || []);
    // autoChangeBg.value = copyJSON(bgInfo.autoChangeBg || {});

    if (!isPhone()) {
        page.value.pageSize = 8
    }


    getBgImg();
}

const dealImgData = (imgApiRes) => {
    const pageNo = page.value.pageNo
    const pageSize = page.value.pageSize

    if (imgApiRes.code != '0') {
        return;
    }
    if (pageNo == 1) {
        showList.value = [];
    }

    let imgList = imgApiRes.data.list || []

    if (bgSource.value == 'my') {
        // 参数增加，不然原图都太大
        imgList.forEach(item => {
            // item.imgUrl = serverConfig.baseURL + item.imgUrl + '?' + scaleImgStr
            item.imgUrl = item.imgUrl + '?' + scaleImgStr
        })
    }

    showList.value = showList.value.concat(imgList);

    // 数据全部加载完成
    if (imgList.length == 0) {
        getImgsEnd.value = true;
        infoToast('没有更多了');
        return
    }

    if (pageSize > imgList.length) {
        getImgsEnd.value = true;
    }
}

const activeMyTag = ref('')
const getBgImg = () => {
    const imgType = getDeviceType();
    const pageNo = page.value.pageNo
    const pageSize = page.value.pageSize

    if (bgSource.value == 'by') {
        getByImgsApi(imgType, pageNo, pageSize).then(imgApiRes => {
            dealImgData(imgApiRes)
        })
    } else if (bgSource.value == 'my') {
        getImgsApi(imgType, activeMyTag.value, pageNo, pageSize).then(imgApiRes => {
            dealImgData(imgApiRes)
        })
    }
};

const moreImg = () => {
    if (getImgsEnd.value) {
        infoToast('没有更多了')
        return;
    }
    page.value.pageNo += 1;
    getBgImg();
}


const setBgImg = (img) => {

    bgImgList.value.forEach((item) => {
        // 其他的壁纸默认取消选择
        item.checked = false;
    })

    // 去掉后面设置的宽度参数
    if (bgSource.value == 'my') {
        // 参数增加，不然原图都太大
        img.imgUrl = img.imgUrl.replace(scaleImgStr, '')
    }

    // 校验一下url如果一样就不去重复添加了
    const existImgs = bgImgList.value.filter(item => item.url === img.imgUrl)
    if (existImgs.length > 0) {
        // exist => update
        const img = existImgs[0]
        img.checked = true;
        img.name = img.imgName;
    } else {
        // not exist => add
        bgImgList.value.push(
            {
                uuid: generateUUID(),
                checked: true,
                name: img.imgName,
                url: img.imgUrl
            }
        );
    }
    bgInfo.urls = bgImgList.value;
    bgInfo.showType = 'url'
    setBgInfo();
}

const setBgColor = (color) => {
    bgInfo.color = color;
    bgInfo.showType = 'color';
    setBgInfo()
}

const openAddModel = () => {
    openItem.value = {
        checked: true, // 默认选中
        url: '',
        name: '',
        uuid: generateUUID()
    }
    activeBgImgIndex.value = -1;
    editDialog.value = true;
}
const saveBgImgUrl = () => {
    // console.log(openItem.value);
    // this.editDialog = false;
    // if (this.activeBgImgIndex === -1) {
    //     this.bgImgList.push(this.openItem);
    // } else {
    //     // this.bgImgList[this.activeBgImgIndex] = this.openItem;
    //     this.$set(this.bgImgList, this.activeBgImgIndex, this.openItem); // 触发更新
    // }
    if (activeBgImgIndex.value === -1) {
        // add
        bgImgList.value.push(openItem.value);
    } else {
        // update
        bgImgList.value[activeBgImgIndex.value] = openItem.value;
    }
    bgInfo.urls = bgImgList.value;
    bgInfo.showType = 'url';
    setBgInfo();
    editDialog.value = false;
}

const setBgInfo = () => {
    user.value.extInfo.bg[deviceType] = bgInfo
    setBg();
    saveUser2Db();
}

const resetConfirm = () => {
    showConfirm({ content: '确认恢复默认吗？' }).then(() => {
        resetBgImgUrl();
    }).catch(() => { })
    // this.$confirm({
    //     content: '确认恢复默认吗？',
    // }, () => {
    //     this.resetBgImgUrl();
    // });
}

const resetBgImgUrl = () => {
    if (isPhone()) {
        bgImgList.value = getBgImgUrlMobileDefault()
    } else {
        bgImgList.value = getBgImgUrlPcDefault()
    }
    bgInfo.urls = bgImgList.value;
    bgInfo.showType = 'url'
    setBgInfo();
}

const upLoadSuccess = (url) => {
    openItem.value.url = url;
    if (isEmpty(openItem.value.name)) {
        openItem.value.name = '自定义背景';
    }
}


onMounted(() => {
    activeTabIndex.value = 0;
    init();
})

watch(bgSwitch, () => {
    bgInfo.showType = bgSwitch.value ? 'url' : 'none'
    setBgInfo();
})


// watch(autoChangeBg, () => {
//     debugger
//     bgInfo.autoChangeBg = autoChangeBg.value
//     setBgInfo();
// })


watch(() => autoChangeBg, () => {
    if (!autoChangeBg.value.interval) {
        autoChangeBg.value.interval = 30
    }
    bgInfo.autoChangeBg = autoChangeBg.value
    setBgInfo();
}, { deep: true })

const bgSource = ref('by')
const myBgTags = ref([])
watch(bgSource, () => {
    getImgsEnd.value = false
    page.value.pageNo = 1

    if (bgSource.value == 'by') {
        getBgImg()
    } else if (bgSource.value == 'my') {
        getImgTagsApi(deviceType).then(res => {
            myBgTags.value = []
            res.data.forEach((item) => {
                myBgTags.value.push({
                    title: item.tagName,
                    uuid: generateUUID()
                })
            })
            nextTick(() => {
                activeMyTag.value = myBgTags.value[0].title
                getBgImg()
            })
        })
    }
})

</script>

<template>
    <!-- <div class="container bg-white bg-opacity-90 my-10 rounded b"> -->
    <!-- backdrop-blur-sm -->
    <div class="h-container">
        <div class="m-5">
            <header class="border-l-8 border-green-500 py-3 pl-4 bg-green-200 rounded italic tracking-widest">
                <span class="text-indigo-500 cursor-pointer" @click="go2Router('home')">主页</span>
                <span class="mx-2">/</span>
                <span>主题设置</span>
            </header>

            <section class="mt-4">

                <div class="w-full py-3 pl-4 bg-green-200 text-sm rounded text-green-900 tracking-widest mb-2 flex">
                    <div class="mr-2">背景开关</div>
                    <div class="flex">
                        <div class="flex justify-center items-center">
                            <input @click="bgSwitch = true" :checked="bgSwitch" type="radio" name="switchBgCheck"
                                class="mr-2" id="checkBgTrue" /><label for="checkBgTrue" class="cursor-pointer">打开</label>
                        </div>
                        <div class="flex justify-center items-center cursor-pointer ml-2">
                            <input @click="bgSwitch = false" :checked="!bgSwitch" type="radio" name="switchBgCheck"
                                class="mr-2" id="checkBgFalse" /><label for="checkBgFalse" class="cursor-pointer">关闭</label>
                        </div>
                    </div>
                </div>

                <div class="w-full py-3 pl-4 bg-green-200 text-sm rounded text-green-900 tracking-widest mb-2 flex">
                    <div class="mr-2">自动更换背景</div>
                    <div class="flex">
                        <div class="flex justify-center items-center">
                            <input @click="autoChangeBg.isOpen = true" :checked="autoChangeBg.isOpen" type="radio"
                                class="mr-2" id="autoChangeBgTrue" /><label for="autoChangeBgTrue"
                                class="cursor-pointer">打开</label>
                        </div>
                        <div class="flex justify-center items-center cursor-pointer ml-2">
                            <input @click="autoChangeBg.isOpen = false" :checked="!autoChangeBg.isOpen" type="radio"
                                class="mr-2" id="autoChangeBgFalse" /><label for="autoChangeBgFalse"
                                class="cursor-pointer">关闭</label>
                        </div>
                    </div>
                </div>

                <div class="flex justify-start mb-4">
                    <div v-for="(item, index) in navList" :key="item.uuid" :index="index" @click="navClick(index, $event)"
                        name="nav"
                        :class="`p-3 ${index == 0 ? 'border-b-4 text-green-500' : ''} border-green-500 text-sm tracking-widest cursor-pointer hover:bg-green-50 hover:text-green-500 transition`">
                        {{ item.title }}
                    </div>
                </div>

                <div v-show="activeTabIndex === 0">

                    <div class="w-full py-3 pl-4 bg-green-200 text-sm rounded text-green-900 tracking-widest mb-2 flex">
                        <div class="mr-2">壁纸来源</div>
                        <div class="flex">
                            <div class="flex justify-center items-center">
                                <input @click="bgSource = 'by'" :checked="bgSource == 'by'" type="radio" class="mr-2"
                                    id="bgSourceBy" /><label for="bgSourceBy" class="cursor-pointer">必应</label>
                            </div>
                            <div class="flex justify-center items-center cursor-pointer ml-2">
                                <input @click="bgSource = 'my'" :checked="bgSource == 'my'" type="radio" class="mr-2"
                                    id="bgSourceMy" /><label for="bgSourceMy" class="cursor-pointer">网络</label>
                            </div>
                        </div>
                    </div>

                    <div class="w-full py-3 pl-4 bg-green-200 text-sm rounded text-gray-500 tracking-widest">
                        <p>{{ bgSource == 'by' ? '以下图片来自必应，每天更新一张' : '以下图片来自网络，每天自动更新' }}</p>
                    </div>

                    <div v-if="bgSource == 'my'" class=" overflow-auto flex justify-start flex-nowrap md:flex-wrap">
                        <div v-for="(item, index) in myBgTags" :key="item.uuid" :index="index"
                            @click="mytagClick(index, $event)" name="tagnav"
                            :class="`whitespace-nowrap p-3 ${index == 0 ? 'border-b-4 text-green-500' : ''} border-green-500 text-sm tracking-widest cursor-pointer hover:bg-green-50 hover:text-green-500 transition`">
                            {{ item.title }}
                        </div>
                    </div>

                    <div class="grid grid-cols-2 md:grid-cols-4 mt-4">
                        <div v-for="(item, index) in showList" :key="item.imgUrl" @click="setBgImg(item)"
                            class="w-full bg-cover bg-center bg-no-repeat flex items-end cursor-pointer relative h-80 md:h-56"
                            @mouseover="byImgHoverIndex = index" @mouseout="byImgHoverIndex = null" :style="{
                                backgroundImage: 'url(' + item.imgUrl + ')'
                            }">
                            <div class="text-white w-full p-2 text-sm bg-black bg-opacity-20 truncate"
                                :title="item.imgName">
                                {{ item.imgName }}
                            </div>
                            <div :style="{
                                height: byImgHoverIndex === index ? '100%' : 0
                            }"
                                class="flex justify-center items-center opacity-40 absolute w-full bg-black transition-all duration-200">
                                <span v-show="byImgHoverIndex === index" class="text-3xl text-white">设置背景</span>
                            </div>
                        </div>
                    </div>

                    <div class="mt-4 text-center" v-show="!getImgsEnd">
                        <div class="cursor-pointer inline-block hover:text-green-500" @click="moreImg">
                            <i aria-hidden="true" class="fas fa-angle-down animate-bounce"></i>
                            <span>加载更多</span>
                            <i aria-hidden="true" class="fas fa-angle-down animate-bounce"></i>
                        </div>
                    </div>
                </div>

                <div v-show="activeTabIndex === 1">
                    <div class="w-full">
                        <div class="grid grid-cols-1 md:grid-cols-4">
                            <div v-for="(item, index) in bgColors" :key="item.color" :index="index"
                                class="h-52 flex justify-center items-center cursor-pointer" :style="{
                                    backgroundColor: item.color,
                                }" @click="setBgColor(item.color)">
                                {{ item.name }}
                            </div>
                        </div>
                    </div>
                </div>

                <div v-show="activeTabIndex === 2">

                    <div class="w-full py-3 pl-4 bg-green-200 text-sm rounded text-gray-500 tracking-widest">
                        <p>1.下面是我收集的一些随机壁纸链接哦，如果你也有好的壁纸链接，欢迎分享<i class="fa fa-envelope"></i>heartaotime@foxmail.com
                            哦</p>
                        <p>2.可以多选，每次刷新页面会从选中的链接中随机获取一个</p>
                        <p>3.你也可以自己设置壁纸的链接哦</p>
                        <p>4.<a class="text-green-500" href="https://blog.jixiaob.cn/?post=93"
                                target="_baank">点我</a>去获取更多随机壁纸链接</p>
                    </div>


                    <div class="h-12 w-full flex justify-center items-center my-2 space-x-3">
                        <button type="button" @click="openAddModel()" class="btn btn-primary">
                            新增一个
                        </button>
                        <button type="button" @click="resetConfirm()" class="btn btn-warning">
                            恢复默认
                        </button>
                    </div>


                    <div class="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
                        <div v-for="( item, index ) in  bgImgList " :key="item.uuid" :index="index" class="shadow-md">
                            <div>
                                <div class="w-full h-56 bg-cover bg-center bg-no-repeat flex items-end cursor-pointer rounded relative"
                                    @click="checkBg(index)" :style="{
                                        backgroundImage: 'url(' + item.url + ')'
                                    }
                                        ">
                                    <div class="text-white w-full p-2 text-sm bg-black bg-opacity-20 truncate"
                                        :title="item.name">
                                        {{ item.name }}
                                    </div>

                                    <div :style="{
                                        height: item.checked ? '100%' : 0
                                    }
                                        "
                                        class="flex justify-center items-center opacity-40 absolute w-full bg-black rounded transition-all duration-200">
                                        <i v-show="item.checked" class="fa fa-check text-5xl text-white"></i>
                                    </div>
                                </div>
                                <div class="h-12 w-full flex justify-end items-center pr-2 space-x-3">
                                    <button type="button" @click="openEditModel(index)" class="btn btn-primary">
                                        编辑
                                    </button>
                                    <button type="button" @click="openDelModel(index)" class="btn btn-warning">
                                        删除
                                    </button>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </section>

            <h-pop :show="editDialog" @close="editDialog = false" :style-set="{ top: '10%', maxWidth: '800px' }">
                <template #header>
                    <div>编辑</div>
                </template>
                <template #main>
                    <div class="grid grid-cols-1 md:gap-y-5">
                        <h-input v-model="openItem.name" label="背景图名称："></h-input>
                        <h-input v-model="openItem.url" label="背景图链接：">
                            <template #right>
                                <div class="btn btn-primary w-20 py-2.5 flex items-center justify-center text-lg cursor-pointer"
                                    @click="uploadEle.click()">
                                    <i class="fas fa-cloud-upload-alt"></i>
                                </div>
                                <h-upload ref="uploadEle" @upLoadSuccess="upLoadSuccess"></h-upload>
                            </template>
                        </h-input>
                        <div class="flex justify-center items-center mt-2 md:mt-0">
                            <img :src="openItem.url" class="max-h-40 cursor-pointer rounded" @click="go2Link(openItem.url)">
                        </div>
                    </div>
                </template>
                <template #footer>
                    <div class="h-12 w-full flex justify-end items-center pr-2 space-x-4">
                        <button type="button" @click="editDialog = false" class="btn btn-secondary">
                            关闭
                        </button>
                        <button type="button" @click="saveBgImgUrl()" class="btn btn-primary">
                            保存
                        </button>
                    </div>
                </template>
            </h-pop>
        </div>
    </div>
</template>

<style scoped>

</style>
